#!/bin/bash

# 设置阈值
THRESHOLD=100000 # 100kB/s，转换为字节
MONITOR_INTERVAL=5 # 5秒
IDLE_THRESHOLD=200 # 200秒

# 获取当前连接的Wi-Fi网络名
get_current_wifi() {
    /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk -F': ' '/ SSID/{print $2}'
}

# 获取信号最强的Wi-Fi网络
get_strongest_wifi() {
    /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s | awk '
    NR > 1 {
        if ($3 > max_signal) {
            max_signal = $3
            ssid = $1
        }
    }
    END { print ssid }' | xargs
}

# 连接到指定的Wi-Fi网络
connect_to_wifi() {
    local ssid="$1"
    echo "Connecting to Wi-Fi network: $ssid"
    if networksetup -setairportnetwork en0 "$ssid"; then
        echo "Successfully connected to $ssid"
    else
        echo "Could not find network $ssid."
        exit 1
    fi
}

# 获取当前网速
get_network_speed() {
    local interface="en0"
    local rx_bytes_start=$(netstat -ib | grep "$interface" | awk '{print $7}' | head -n 1)
    local tx_bytes_start=$(netstat -ib | grep "$interface" | awk '{print $10}' | head -n 1)

    sleep $MONITOR_INTERVAL

    local rx_bytes_end=$(netstat -ib | grep "$interface" | awk '{print $7}' | head -n 1)
    local tx_bytes_end=$(netstat -ib | grep "$interface" | awk '{print $10}' | head -n 1)

    local rx_speed=$((($rx_bytes_end - $rx_bytes_start) / $MONITOR_INTERVAL))
    local tx_speed=$((($tx_bytes_end - $tx_bytes_start) / $MONITOR_INTERVAL))

    echo "$rx_speed $tx_speed"
}

# 主监测函数
monitor_network() {
    local last_active_time=$(date +%s)
    local current_wifi=""

    while true; do
        local ssid=$(get_current_wifi)
        if [ "$ssid" != "$current_wifi" ]; then
            current_wifi="$ssid"
            echo "Current Wi-Fi network: $current_wifi"
        fi

        if [ -z "$ssid" ]; then
            echo "No Wi-Fi networks found."
            sleep 60
            continue
        fi

        connect_to_wifi "$ssid"

        sleep 10 # 等待连接稳定

        while true; do
            local net_speed=($(get_network_speed))
            local rx_speed=${net_speed[0]}
            local tx_speed=${net_speed[1]}
            local current_time=$(date +%s)
            local elapsed_time=$((current_time - last_active_time))

            echo "Wi-Fi: $ssid - Download Speed: $((rx_speed / 1024)) kB/s - Upload Speed: $((tx_speed / 1024)) kB/s"

            if (( rx_speed > THRESHOLD || tx_speed > THRESHOLD )); then
                last_active_time=$current_time
            fi

            if (( elapsed_time > IDLE_THRESHOLD )); then
                break
            fi

            sleep $MONITOR_INTERVAL
        done
    done
}

# 开始监测
monitor_network
